/*  GStruct: data structure helpers for Java
 *  Copyright (C) 2011 Giulio Franco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package gstruct.cli.propbased;

import gstruct.cli.CLIArgument;
import gstruct.cli.CLICommand;
import gstruct.cli.ParseResult;

import java.util.Iterator;
import java.util.Properties;

/**
 * CLICommand implementation that stores its result
 * in a {@link Properties} object.
 * @author Giulio Franco <giulio_franco@msn.com>
 */
public abstract class CLIPropCommand
		extends CLICommand<Properties, Properties> {
	/**
	 * Key that will be used to store the command name
	 * if the command is found in the arguments
	 * a different key can be specified by using the constructor
	 * {@link #CLIPropCommand(String, String, String, CLIArgument...)}
	 */
	public static final String DEFAULT_COMMAND_KEY = "command";
	
	private final String key;
	
	/**
	 * Creates a CLIPropcommand
	 * @param name	Command name
	 * @param description	Command description
	 * @param args	Arguments supported by the command
	 */
	public CLIPropCommand(String name, String description,
			CLIArgument<? super Properties>... args) {
		this(name, description, DEFAULT_COMMAND_KEY, args);
	}
	
	/**
	 * Creates a CLIPropcommand
	 * @param name	Command name
	 * @param description	Command description
	 * @param key	Key that will be used to store the command name
	 * 				if the command is found in the arguments
	 * @param args	Arguments supported by the command
	 */
	public CLIPropCommand(String name, String description, String key,
			CLIArgument<? super Properties>... args) {
		super(name, description, args);
		this.key = key;
	}

	@Override
	protected Properties createResult() {
		return new Properties();
	}

	@Override
	protected boolean commandInserted(Iterator<String> args,
			ParseResult<? extends Properties> result,
			ParseResult<Properties> innerResult) {

		result.getResult().putAll(innerResult.getResult());
		result.getResult().setProperty(key, getName());
		
		return true;
	}
	
	/**
	 * Gets the key that will be used
	 * to store the name of the command
	 * if the command is found in the arguments
	 * @return	Command key
	 */
	public String getKey() {
		return key;
	}
}
